<?php

namespace App\Http\Controllers\Api;


use App\Models\BuyLog;
use App\Models\Live;
use App\Models\LiveChannel;
use App\Support\TradeUtil;
use App\Traits\WeChat\WechatDefaultConfig;
use App\WeChat\Order\UnifiedOrder;
use App\WeChat\Response\UnifiedOrderResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LiveController extends BaseController
{
    use WechatDefaultConfig;

    public function get(Request $request)
    {
        $live = Live::findOrFail($request->input('id'));
        $live->increment('views');
        return ajaxReturn(['live' => $live]);
    }

    public function batchget(Request $request)
    {
        $items = Live::filter($request->all())->offset($request->input('offset', 0))
            ->limit($request->input('count', 10))
            ->orderByDesc('id')->get();

        return ajaxReturn(['items' => $items]);
    }

    public function getChannel(Request $request)
    {
        $channel = LiveChannel::findOrFail($request->input('channel_id'));
        return ajaxReturn(['channel' => $channel]);
    }

    public function batchgetChannel(Request $request)
    {
        return ajaxReturn(['items' => LiveChannel::all()]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function canPlay(Request $request)
    {
        $live = Live::find($request->input('live_id'));
        if ($live->watch_mode == 1) {
            return ajaxReturn(['canplay' => true]);
        }

        if ($live->uid == Auth::id()) {
            return ajaxReturn(['canplay' => true]);
        }

        if (Auth::user()->isAdmin()) {
            return ajaxReturn(['canplay' => true]);
        }

        if (BuyLog::where(['uid' => Auth::id(), 'buyable_type' => 'live', 'buyable_id' => $live->id])->exists()) {
            return ajaxReturn(['canplay' => true]);
        }

        return ajaxReturn(['canplay' => false]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function buyTicket(Request $request)
    {
        $live = Live::find($request->input('live_id'));
        $payment = $this->payment();
        $unifiedOrder = new UnifiedOrder();
        $unifiedOrder->setBody('云州直播-' . $live->title)
            ->setOutTradeNo(TradeUtil::createOrderNo())
            ->setTotalFee($live->price * 100)
            ->setAttach($live->id)
            ->setOpenid(session('wechat_user.openid'))
            ->setTradeType($payment->config->get('trade_type', 'JSAPI'))
            ->setNotifyUrl(url('notify/wechat/liveticket'));
        $res = new UnifiedOrderResponse($payment->order->unify($unifiedOrder->getBizContent()));
        if ($res->tradeSuccess()) {
            return ajaxReturn(['config' => $payment->jssdk->bridgeConfig($res->prepayId(), false)]);
        } else {
            return ajaxError(500, $res->errCodeDes() ?: '', ['extra' => $res->all()]);
        }
    }
}
